package com.pig4cloud.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@EnableConfigurationProperties(value = {WxMaProperties.class, WxPayProperties.class})
public class WxMaConfiguration {


	private final WxMaProperties properties;
	private final WxPayProperties payProperties;

	@Autowired
	public WxMaConfiguration(WxMaProperties properties, WxPayProperties wxPayProperties) {
		this.properties = properties;
		this.payProperties = wxPayProperties;
	}

	@Bean
	public WxMaService wxMaService() {
		List<WxMaProperties.Config> configs = this.properties.getConfigs();
		if (configs == null) {
			throw new WxRuntimeException("配置不存在,请检查配置 参考地址: https://github.com/binarywang/weixin-java-miniapp-demo/blob/master/src/main/resources/application.yml.template！");
		}
		WxMaService maService = new WxMaServiceImpl();
		maService.setMultiConfigs(
				configs.stream()
						.map(a -> {
							WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
							//WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
							// 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
							config.setAppid(a.getAppid());
							config.setSecret(a.getSecret());
							// 微信小程序消息
							//config.setToken(a.getToken());
							//config.setAesKey(a.getAesKey());
							//config.setMsgDataFormat(a.getMsgDataFormat());
							return config;
						}).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
		return maService;
	}

//	@Bean
//	public WxPayService wxService() {
//		WxPayConfig payConfig = new WxPayConfig();
//		payConfig.setAppId(StringUtils.trimToNull(this.payProperties.getAppId()));
//		payConfig.setMchId(StringUtils.trimToNull(this.payProperties.getMchId()));
//		payConfig.setMchKey(StringUtils.trimToNull(this.payProperties.getMchKey()));
//		payConfig.setKeyPath(StringUtils.trimToNull(this.payProperties.getKeyPath()));
//		payConfig.setPrivateKeyPath(StringUtils.trimToNull(this.payProperties.getPrivateKeyPath()));
//		payConfig.setPrivateCertPath(StringUtils.trimToNull(this.payProperties.getPrivateCertPath()));
//		payConfig.setApiV3Key(StringUtils.trimToNull(this.payProperties.getApiV3Key()));
//		// 可以指定是否使用沙箱环境
//		payConfig.setUseSandboxEnv(false);
//
//		WxPayService wxPayService = new WxPayServiceImpl();
//		wxPayService.setConfig(payConfig);
//		return wxPayService;
//	}
}
